import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity, Image, ScrollView, Dimensions } from "react-native";
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { ApproveRefuseModal } from '../../order/approve/details/modals/refuse';
import ToastUtil from '../../../utils/toast';
import StockService from "../_common/service";
import ModalPicsComponent from '../../customer-management/enterprise/details/_components/ModalPicsComponent';
import moment from 'moment';


const scale = GLOBAL.SCALE;

const modalPicDelCfg = {
	visible: false,
	urls: [],
	picPress: () => { },
}

export class QhPostponeDetialsPage extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '泉化担保日延期审批详情',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				fontSize: 18 * scale,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props)
		this.state = {
			status: 'data',
			detail: null,
			refuseModalVisible: false,
		}
		this.pageParams = this.props.navigation.state.params || {};
	}

	componentWillMount() {
		this.initPage();
	}

	initPage = async () => {
		this.setState({
			status: 'loading'
		})
		let response = await StockService.qhPostponeDetails({ changeId: this.pageParams.changeId });
		console.log("response:", response)
		if (response) {
			this.setState({
				detail: response,
				status: 'data'
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}




	_audit = async () => {
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;
		const responseData = await StockService.qhChangeAuto({
			auditResult: this.isAgreed,
			remark: this.remark, // 填写
			changeId: this.changeId,
			changeType: this.changeType
		})
		this.setState({ loaded: false });
		console.log('responseData', responseData)
		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == 0) ? '驳回成功' : '审批成功').then(() => {
				this.requesting = false;
				this.props.navigation.goBack();
			})
		} else {
			this.requesting = false;
		}
	}

	_pass(data) {
		let { changeId, changeType } = data;
		this.isAgreed = 1;
		this.remark = '';
		this.changeId = changeId;
		this.changeType = changeType;
		this.setState({
			refuseModalVisible: true
		})
	}

	_refuse(data) {
		let { changeId, changeType } = data;
		this.isAgreed = 0;
		this.remark = '';
		this.changeId = changeId;
		this.changeType = changeType;
		this.setState({
			refuseModalVisible: true
		})
	}





	//查看合同
	_previeContract(id) {
		this.props.navigation.navigate('ContractPdfPage', { finalFileId: id })
	}
	//查看附件
	_previeAnnex(data) {
		const { fileName, fileId } = data;
		console.log("fileName", fileName)
		if (fileName.indexOf('.pdf') != -1) {
			this.props.navigation.navigate('ContractPdfPage', { finalFileId: fileId });
		} else {
			this._getImgPreview(fileId);
		}
	}
	//附件预览
	async _getImgPreview(fileId) {
		const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
		if (response && response.image && response.image.length) {
			modalPicDelCfg.visible = true;
			modalPicDelCfg.urls[0] = {
				url: response.image,
				width: Dimensions.get('window').width
			};
			modalPicDelCfg.picPress = () => {
				modalPicDelCfg.visible = false;
				modalPicDelCfg.urls = [];
				this.setState({
					previewModalVisible: false,
				});
			}
			this.setState({ ls: true });
		}
	}




	render() {
		let { status, detail } = this.state;
		let { companyName, createTime, createName, orderId, inNoticeId,
			outStockEndDate, expectExeDate, isDirectSelling, deliveryTypeName, transportTypeName, remark, sheetFileList, inStockNoticeItemVOList,
			salesmanName, companySendDate, organName, changeId, changeType } = detail || {};
		if (createTime) {
			createTime = createTime.split(" ")[0];
		}
		return (
			<View style={styles.container}>
				{
					status === 'data' ? <ScrollView style={styles.container}>
						<View style={styles.topContainer}>
							<View style={styles.topInfoView}>
								<View style={styles.topInfoTextView}>
									<Text style={[styles.topInfoLabel, { marginBottom: 12 * scale }]}>变更单号：</Text>
									<Text style={[styles.topInfoValue, { marginBottom: 12 * scale }]}>{changeId || '-'}</Text>
								</View>
								<View style={styles.topInfoTextView}>
									<Text style={styles.topInfoLabel}>订单号：</Text>
									<Text style={styles.topInfoValue}>{orderId || '-'}</Text>
								</View>
							</View>
							<View style={styles.buttonBox}>
								<TouchableOpacity style={styles.buttonPass} activeOpacity={1} onPress={() => {
									this._pass({ changeId, changeType });
								}}>
									<Text style={styles.buttonPassText}>通过</Text>
								</TouchableOpacity>
								<TouchableOpacity style={styles.buttonRefuse} activeOpacity={1} onPress={() => {
									this._refuse({ changeId, changeType });
								}}>
									<Text style={styles.buttonRefuseText}>驳回</Text>
								</TouchableOpacity>
							</View>
						</View>

						<View style={styles.mb20}>
							<View style={styles.hezi}>
								<View style={styles.item}>
									<Text style={styles.commonTitle}>{changeType === "inStockNotice" ? "供应商名称" : "客户名称"}</Text>
									<Text style={styles.commonText}>{companyName || '-'}</Text>
								</View>
								<View style={styles.item}>
									<Text style={styles.commonTitle}>供应商发货日期</Text>
									<Text style={styles.commonText}>{companySendDate && moment(companySendDate).format("YYYY-MM-DD")}</Text>
								</View>
								{
									changeType === "outStockNotice" ? <View style={styles.item}>
										<Text style={styles.commonTitle}>关联入库单据号</Text>
										<Text style={styles.commonText}>{inNoticeId}</Text>
									</View> : null
								}
								{
									changeType === "outStockNotice" ? <View style={styles.item}>
										<Text style={styles.commonTitle}>有效出库日期</Text>
										<Text style={styles.commonText}>{outStockEndDate && moment(outStockEndDate).format("YYYY-MM-DD")}</Text>
									</View> : null
								}
								{
									changeType === "inStockNotice" ? <View style={styles.item}>
										<Text style={styles.commonTitle}>预计收货日期</Text>
										<Text style={styles.commonText}>{expectExeDate && moment(expectExeDate).format("YYYY-MM-DD")}</Text>
									</View> : null
								}
								<View style={styles.item}>
									<Text style={styles.commonTitle}>是否直销</Text>
									<Text style={styles.commonText}>{isDirectSelling == "1" ? "是" : "否"}</Text>
								</View>
								<View style={styles.item}>
									<Text style={styles.commonTitle}>交货方式</Text>
									<Text style={styles.commonText}>{deliveryTypeName}</Text>
								</View>
								<View style={styles.item}>
									<Text style={styles.commonTitle}>运输方式</Text>
									<Text style={styles.commonText}>{transportTypeName}</Text>
								</View>
								<View style={styles.item}>
									<Text style={styles.commonTitle}>申请人</Text>
									<Text style={styles.commonText}>{createName}</Text>
								</View>
								<View style={styles.item}>
									<Text style={styles.commonTitle}>申请日期</Text>
									<Text style={styles.commonText}>{createTime && moment(createTime).format("YYYY-MM-DD")}</Text>
								</View>
								<View style={styles.item}>
									<Text style={styles.commonTitle}>业务员</Text>
									<Text style={styles.commonText}>{salesmanName} ({organName})</Text>
								</View>
								<View style={styles.item}>
									<Text style={styles.commonTitle}>备注</Text>
									<Text style={styles.commonText}>{remark}</Text>
								</View>
							</View>

						</View>

						<Text style={styles.changeTitleAll}>变更信息</Text>

						{
							inStockNoticeItemVOList && inStockNoticeItemVOList.length && inStockNoticeItemVOList.map((item, index) => {
								let { sapSnNo, goodsName, sapPusherTime, planId, noticeQuantity, okAmount, icAmount, expectExeDateBrfore, warrantDateAfter, warrantDateBrfore, expectExeDateAfter, outStockEndDateBrfore, outStockEndDateAfter } = item
								return <View key={index} style={styles.changeBox}>
									<View style={styles.changeLine}>
										<View style={styles.changeItem}>
											<Text style={styles.changeTitle}>SAP订单号</Text>
											<Text style={styles.changeValue}>{sapSnNo}</Text>
										</View>
										<View style={styles.changeItem}>
											<Text style={styles.changeTitle}>推送日期</Text>
											<Text style={styles.changeValue}>{sapPusherTime && moment(sapPusherTime).format("YYYY-MM-DD")}</Text>
										</View>
										<View style={styles.changeItem}>
											<Text style={styles.changeTitle}>商品名称</Text>
											<Text style={styles.changeValue}>{goodsName}</Text>
										</View>
									</View>
									<View style={styles.changeLine}>
										<View style={styles.changeItem}>
											<Text style={styles.changeTitle}>商品数量（吨）</Text>
											<Text style={styles.changeValue}>{noticeQuantity}</Text>
										</View>
										<View style={styles.changeItem}>
											<Text style={styles.changeTitle}>已开计划量（吨）</Text>
											<Text style={styles.changeValue}>{icAmount}</Text>
										</View>
										<View style={styles.changeItem}>
											<Text style={styles.changeTitle}>提货系统实发量（吨）</Text>
											<Text style={styles.changeValue}>{okAmount}</Text>
										</View>
									</View>
									<View style={styles.changeLine}>
										<View style={[styles.changeItem, { width: "100%" }]}>
											<Text style={styles.changeTitle}>运输委托号</Text>
											<Text style={styles.changeValue}>{planId}</Text>
										</View>
									</View>


									<View style={styles.changeLine}>
										<Text style={[styles.itemTitle, styles.itemColor]}>担保日期</Text>
										<View style={styles.itemValueBox}>
											<Text style={[styles.itemValue]}>{warrantDateBrfore}</Text>
											<Text style={styles.arrow}>—></Text>
											<Text style={[styles.itemValue, styles.textNew]}>{warrantDateAfter}</Text>
										</View>
									</View>
									<View style={styles.changeLine}>
										<Text style={[styles.itemTitle, styles.itemColor]}>{changeType === "inStockNotice" ? "预计收货日期" : "有效出库日期"}</Text>
										<View style={styles.itemValueBox}>
											<Text style={[styles.itemValue]}>{changeType === "inStockNotice" ? expectExeDateBrfore : outStockEndDateBrfore}</Text>
											<Text style={styles.arrow}>—></Text>
											<Text style={[styles.itemValue, styles.textNew]}>{changeType === "inStockNotice" ? expectExeDateAfter : outStockEndDateAfter}</Text>
										</View>
									</View>

								</View>
							})
						}

						<View style={styles.mb20}>
							<Text style={styles.changeTitleAll}>变更附件</Text>
							<View style={styles.attachmentBox}>
								{
									sheetFileList && sheetFileList.length ? (
										sheetFileList.map((item, index) => {
											return <Text key={index} style={styles.attachment} onPress={() => { this._previeAnnex(item) }}>[{item.fileName}]</Text>
										})
									) : <Text style={styles.attachmentActive}>无</Text>
								}
							</View>
						</View>

					</ScrollView> : <View style={{ flex: 1 }}>
							<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.initPage} />
						</View>
				}

				<ApproveRefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._audit();
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />


				<ModalPicsComponent {...modalPicDelCfg} />

			</View>

		)
	}

}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	buttonPass: {
		width: 60 * scale,
		backgroundColor: style.color.themeColor,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginRight: 10 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 60 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
	},
	topContainer: {
		flexDirection: 'row',
		paddingTop: 18 * scale,
	},
	topInfoView: {
		flex: 1,
		paddingLeft: 14 * scale
	},
	topInfoTextView: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	topInfoLabel: {
		color: '#080808',
		fontSize: 12 * scale,
		textAlign: 'right',
		width: "32%",
	},
	topInfoValue: {
		color: '#080808',
		fontSize: 12 * scale,
		fontWeight: '700',
		flexWrap: 'wrap'
	},
	billInfoWrap: {
		flexDirection: 'column',
		alignItems: 'flex-start',
		justifyContent: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 20 * scale,
	},
	commonTitle: {
		flex: 1,
		color: '#000',
		opacity: 0.8,
		fontSize: 10 * scale,
		minWidth: 64 * scale,
	},
	commonText: {
		// width: 108 * scale,
		flex: 1,
		fontSize: 10 * scale,
		color: '#0C0C0D',
		fontWeight: '800',
		paddingTop: 8 * scale
	},
	commonRowLabel: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	commonRowValue: {
		flexDirection: 'row',
		alignItems: 'flex-start'
	},
	changeTitleAll: {
		fontSize: 13 * scale,
		fontWeight: 'bold',
		paddingLeft: 15 * scale,
	},
	changeBox: {
		backgroundColor: '#fff',
		borderRadius: 10 * scale,
		padding: 8 * scale,
		margin: 6 * scale,
		paddingTop: 20 * scale,
		marginBottom: 20 * scale
	},
	changeItem: {
		width: "33%"
	},
	changeTitle: {
		fontSize: 11 * scale,
		color: '#000',
		opacity: 0.8
	},
	changeValue: {
		fontSize: 11 * scale,
		color: '#000',
		paddingTop: 10 * scale
	},
	changeLine: {
		flexDirection: 'row',
		alignItems: 'center',
		marginBottom: 20 * scale
	},

	itemTitle: {
		width: '30%',
	},
	itemValue: {
		fontSize: 13 * scale,
		color: '#000'
	},
	itemValueBox: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	textNew: {
		color: "#CA0202"
	},
	arrow: {
		fontSize: 13 * scale,
		color: "#CA0202",
		paddingHorizontal: 10 * scale
	},
	itemColor: {
		color: '#000',
		opacity: 0.7,
		fontSize: 12 * scale
	},
	mb20: {
		marginBottom: 20 * scale
	},
	attachmentBox: {
		marginVertical: 8 * scale,
		marginHorizontal: 15 * scale,
		paddingBottom: 30 * scale,
		flexDirection: 'row'
	},
	attachment: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
		marginRight: 10 * scale,
		padding: 5 * scale
	},
	attachmentActive: {
		fontSize: 12 * scale
	},
	hezi: { flexDirection: 'row', flexWrap: 'wrap', width: '100%', paddingHorizontal: 10 * scale },
	item: {
		width: "33%",
		paddingTop: 20 * scale
	}
})